<?php 

class Signup_model extends Model
{
	
	function __construct(){
		parent::__construct();
	}

	public function xhrInsert()
	{
		$Birth_Date = strtotime($_POST['month'].'/'.$_POST['day'].'/'.$_POST['year']);
		$Birth_Date = date('d-m-Y',$Birth_Date);
		$error 		= array();
		$FirstName 	= Model::validate_input_text('/^[\w\'.-]{2,20}$/i','FirstName');
		$LastName  	= Model::validate_input_text('/^[\w\'.-]{2,20}$/i','LastName');
		$Email  	= Model::validate_Email('Email');
		$Re_Email  	= Model::validate_Email('Re_Email');
		$Password  	= Model::validate_input_text('/^[\w\'.-]{2,20}$/i','Password');
		$count = 0;

		if($FirstName 	== false) $error[] = 'FirstName';
		if($LastName 	== false) $error[] = 'LastName';
		if($Password 	== false) $error[] = 'Password';
		if($Email 		== false) $error[] = 'Email';
		if($Re_Email 	== false) $error[] = 'Re_Email';

		if($Email){
			$q = $this->db->prepare("SELECT User_Id FROM users WHERE Email = :email ");
			$q->execute(array(
				':email' 	=> 	$Email,
			));

			$count = $q->rowCount();

			if($count != 0){
				$error[] = 'Email';
			}else {
				if($Email != $Re_Email) $error[] = 'Re_Email';
			}
		}


		if(empty($error))
		{
			// MD5 is not even remotely secure
			$pass = md5($_POST['Password']); 
			$q = $this->db->prepare("INSERT INTO users (FirstName,LastName,Email,Password,Gender,Birth_Date) 
							VALUES (:FirstName,:LastName,:Email,:Password,:Gender,:Birth_Date)");
			$value = $q->execute(array(
				':FirstName' 	=> 	$FirstName,
				':LastName'		=>	$LastName,
				':Email' 		=> 	$Email,
				':Password'		=>	$pass,
				':Gender' 		=> 	$_POST['Gender'],
				':Birth_Date'	=>	$Birth_Date
			));
			// return array
			//$data = $q->fetchAll();
			$error[] =  $value;
			if($value){
				$error[] =  true;
				Session::init();
				Session::set('loggerIn',true);
				Model::send_email($Email,'Admin WWG','Minh Le','kick hoat tai khoan WWG','Kick hoat ');
			}
		}else {
			echo json_encode($error);
		}
	}

	public function xhrCheckEmail()
	{
		$q = $this->db->prepare("SELECT User_Id FROM users WHERE Email = :email ");
		$q->execute(array(
			':email' 	=> 	$_POST['email'],
		));
		// return array
		//$data = $q->fetchAll();
		$count = $q->rowCount();
		
		if($count != 0){
			$data = array('success' => 'true');
			echo json_encode($data);
		}else {
			$data = array('success' => 'false');
			echo json_encode($data);
		}
	}
}
?>